package com.penghaisoft.microwms.base.web.expose.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.base.web.auth.service.IUserService;
import com.penghaisoft.microwms.base.web.data.service.IBaseDictionaryService;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.base.model.BaseUser;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.wms.model.ProOrderInSn;

/**
 * @program: micro-wms
 * @description: 免登录接口
 * @author: zhangx
 * @create: 2018-05-08 15:23
 **/
@RestController
@RequestMapping(value = "/expose")
public class ExposeController extends BaseController {

	@Autowired
	private IMesInterfaceService mesInterfaceService;
	
	@Resource
	private MesProperties mesProperties;
	
	@Autowired
    private IUserService userService;
	
	@Autowired
	private IBaseDictionaryService baseDictionaryService;

	@Autowired
	private StringRedisTemplate redisTemplate;// spring-data-redis
	
    /** 
     * @Title add
     * @Description 用户新增
     * @author luoteng
     * @date 2018年7月6日:上午9:45:43
     * @param user
     * @return TransResult
     */
    @RequestMapping(value = "/user/c", method = RequestMethod.POST)
    public TransResult add(@RequestBody BaseUser user) {
    	//user.setCreateBy(getLoginName());
    	user.setGmtCreate(new Date());
    	TransResult transResult = new TransResult();
    	
        Resp resp = userService.addUser(user);
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
    
    /** 
     * @Title update
     * @Description 用户修改
     * @author luoteng
     * @date 2018年7月6日:上午9:46:10
     * @param user
     * @return TransResult
     */
    //@RequestMapping(value = "/user/u", method = RequestMethod.POST)
    @PostMapping("/user/u")
    public TransResult update(@RequestBody BaseUser user) {
    	user.setGmtModified(new Date());
    	TransResult transResult = new TransResult();
    	BaseUser condition = new BaseUser();
    	if(user.getLoginName()==null||user.getLoginName().equals("")){
    		transResult.setCode("0");
            transResult.setMsg("请填写账号");
            return transResult;
    	}else{
    		condition.setLoginName(user.getLoginName());
    		List<BaseUser> list = userService.queryListByLoginName(condition);
    		if(list.size() <= 0){
    			transResult.setCode("0");
                transResult.setMsg("该用户不存在");
                return transResult;
    		}else{
        		user.setUserId(list.get(0).getUserId());
        	}
    	}
//    	String updateName = getLoginName();
//    	System.out.println(updateName);
//    	user.setLastModifiedBy(updateName);

        Resp resp = userService.updateNoMd5(user);
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
    
    /**
     * @Description: 删除(批量)
     * @author zxcq0
     * @date 2017/3/2 15:09
     * @param
     * @return
     */
    @RequestMapping(value = "/user/d", method = RequestMethod.POST)
    public TransResult delete(@RequestBody BaseUser user) {
    	user.setGmtModified(new Date());
        TransResult transResult = new TransResult();
        BaseUser condition = new BaseUser();
        List<String> userIds = new ArrayList<String>();
    	if(user.getLoginName()==null||user.getLoginName().equals("")){
    		transResult.setCode("0");
            transResult.setMsg("请填写账号");
            return transResult;
    	}else{
    		condition.setLoginName(user.getLoginName());
    		List<BaseUser> list = userService.queryListByLoginName(condition);
    		if(list.size() <= 0){
    			transResult.setCode("0");
                transResult.setMsg("该用户不存在");
                return transResult;
    		}else{
        		user.setUserId(list.get(0).getUserId());
        		userIds.add(list.get(0).getUserId());
        	}
    	}
        Resp resp = userService.deleteBatch(userIds);
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
	
	/** 
	 * @Title testProMes
	 * @Description 测试成品 mes条码下线
	 * @author luoteng
	 * @date 2018年6月21日:下午2:05:55 void
	 */
	@PostMapping("mes/test")
    public Map<String, Object> testProMes(){
		List<ProOrderInSn> list = new ArrayList<ProOrderInSn>();
		ProOrderInSn tmp = new ProOrderInSn();
		tmp.setBarcode("ltTest");
		tmp.setActiveFlag("1");
		tmp.setCreateBy("ltMesTest");
		tmp.setGmtCreate(new Date());
		list.add(tmp);
		String jsonString = JSON.toJSONString(list);
		System.out.println(jsonString);
		String url = mesProperties.getUrl() + "/product/expose/mes/proorderinsn/add";
//		调mes新增接口
		Map<String, Object> ob = mesInterfaceService.publicWS(url, 
				MediaType.APPLICATION_JSON_TYPE, jsonString);
		
		return ob;
    }
	
	/** 
	 * @Title testMatNormalMes
	 * @Description 原材料领用单 普通 测试
	 * @author luoteng
	 * @date 2018年6月21日:下午2:08:11 void
	 */
	@PostMapping("mes/normal/test")
    public Map<String, Object> testMatNormalMes(){
		List<RawRequisition> list = new ArrayList<RawRequisition>();
		RawRequisition tmp = new RawRequisition();
		tmp.setRequisitionNo("LTTEST");
		tmp.setModel("L001");
		tmp.setModelDesc("螺纹钢管");
		tmp.setModelType("L");
		tmp.setActiveFlag("1");
		tmp.setCreateBy("ltMesTest");
		tmp.setGmtCreate(new Date());
		list.add(tmp);
		String jsonString = JSON.toJSONString(list);
		System.out.println(jsonString);
		String url = "http://localhost:8092/material/expose/mes/rawrequisition/normal/add";
//		调mes新增接口
		Map<String, Object> ob = mesInterfaceService.publicWS(url, 
				MediaType.APPLICATION_JSON_TYPE, jsonString);
		
		return ob;
    }
	
	/** 
	 * @Title testMatRepairMes
	 * @Description 原材料领用单 返修 测试
	 * @author luoteng
	 * @date 2018年6月21日:下午2:08:11 void
	 */
	@PostMapping("mes/repair/test")
    public Map<String, Object> testMatRepairMes(){
		List<RawRequisition> list = new ArrayList<RawRequisition>();
		RawRequisition tmp = new RawRequisition();
		tmp.setRequisitionNo("LTTEST");
		tmp.setActiveFlag("1");
		tmp.setCreateBy("ltMesTest");
		tmp.setGmtCreate(new Date());
		list.add(tmp);
		String jsonString = JSON.toJSONString(list);
		System.out.println(jsonString);
		String url = "http://localhost:8092/material/expose/mes/rawrequisition/repair/add";
//		调mes新增接口
		Map<String, Object> ob = mesInterfaceService.publicWS(url, 
				MediaType.APPLICATION_JSON_TYPE, jsonString);
		
		return ob;
    }

    @PostMapping("test")
    public String test(){
        String val = getSerialNo(1);
        return val;
    }


    @GetMapping("handChooseSet")
    public String handChooseSet(){
        String handChooseKey = "wms:hand:choose";
        redisTemplate.opsForSet().add(handChooseKey,"1001","1005");
        return handChooseKey;
    }

    @GetMapping("handChooseGet")
    public String handChooseGet(){
        String handChooseKey = "wms:hand:choose";
        boolean flag = redisTemplate.opsForSet().isMember(handChooseKey,"1001");
        System.out.println("1001 is" + flag);
        flag = redisTemplate.opsForSet().isMember(handChooseKey,"2001");
        System.out.println("2001 is" + flag);
        return handChooseKey;
    }

	@GetMapping("monitor/address")
	public JSONObject getMonitorAddress(){
		JSONObject result = new JSONObject();
		String key = Constant.MONITOR_KEY;
		String address = redisTemplate.opsForValue().get(key);
		result.put("address",address);
		return result;
	}

    @GetMapping("modules")
    public Set<Object> getModules(){
        String key = Constant.MODULE_KEY;
        Set<Object> modules = redisTemplate.opsForHash().keys(key);
        return modules;
    }
    
    /**
	 * @Title queryByTypId
	 * @Description 从redis缓存查询下拉框字典
	 * @author luoteng
	 * @date 2017年6月9日:下午3:39:07
	 * @param dicType
	 * @return TransResult
	 */
    @PostMapping("get/{dicType}")
	public TransResult queryRedisByTypId(@PathVariable String dicType) {
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
		List<BaseDictionary> list = JSONArray.parseArray(redisTemplate.opsForValue().get(Constant.DICTIONARY_DICTYPE + dicType),BaseDictionary.class);
		if(list.size() == 0 || list == null){
			dicReload();
			list = JSONArray.parseArray(redisTemplate.opsForValue().get(Constant.DICTIONARY_DICTYPE + dicType),BaseDictionary.class);
		}
		result.setList(list);
		return result;
	}
	
	public void dicReload() {
		//只加载有效的字典
		BaseDictionary tmp = new BaseDictionary();
		tmp.setActiveFlag("1");
		List<BaseDictionary> list = baseDictionaryService.queryAllByCondition(tmp);
		Map<String, List> map = new HashMap<String, List>();
		for(BaseDictionary baseDictionary : list){
			String dicType = baseDictionary.getDicType();
			List<BaseDictionary> tmpList;
			if(map.containsKey(dicType)){
				tmpList = map.get(dicType);
				
			}else{
				tmpList = new ArrayList<BaseDictionary>();
			}
			tmpList.add(baseDictionary);
			map.put(dicType, tmpList);
		}

		redisTemplate.delete(Constant.DICTIONARY_DICTYPE + "*");

		for (String key:map.keySet()){
			redisTemplate.opsForValue().set(Constant.DICTIONARY_DICTYPE + key, JSONObject.toJSONString(map.get(key)));
		}
	}
}
